package com.wofish.goods.service.impl;

import com.wofish.common.constant.Constants;
import com.wofish.common.core.text.Convert;
import com.wofish.common.json.JsonUtil;
import com.wofish.goods.domain.Goods;
import com.wofish.goods.domain.GoodsSpecIndex;
import com.wofish.goods.domain.ImageAttach;
import com.wofish.goods.domain.Products;
import com.wofish.goods.dto.ProductsIndex;
import com.wofish.goods.dto.SpecDescDto;
import com.wofish.goods.mapper.GoodsMapper;
import com.wofish.goods.mapper.ProductsMapper;
import com.wofish.goods.service.IGoodsService;
import com.wofish.goods.service.IGoodsSpecIndexService;
import com.wofish.goods.service.IImageAttachService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 商品 服务层实现
 * 
 * @author wofish
 * @date 2019-05-31
 */
@Service
@Slf4j
public class GoodsServiceImpl implements IGoodsService {
	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private ProductsMapper productsMapper;

	@Autowired
	private IGoodsSpecIndexService goodsSpecIndexService;

	@Autowired
	private IImageAttachService imageAttachService;

	/**
     * 查询商品信息
     * 
     * @param goodsId 商品ID
     * @return 商品信息
     */
    @Override
	public Goods selectGoodsById(Long goodsId) {
	    return goodsMapper.selectGoodsById(goodsId);
	}
	
	/**
     * 查询商品列表
     * 
     * @param goods 商品信息
     * @return 商品集合
     */
	@Override
	public List<Goods> selectGoodsList(Goods goods) {
	    return goodsMapper.selectGoodsList(goods);
	}
	
    /**
     * 新增商品、货品
     * 
     * @param goods 商品信息
     * @return 结果
     */
	@Override
	public int insertGoods(Goods goods) {
		//生成商品
		int row = goodsMapper.insertGoods(goods);
		//保存图片
		saveImageGoods(goods);

		saveProducts(goods);

	    return row;
	}

	private void saveImageGoods(Goods goods){
		//查询是否有关联图片和默认图片
		if (StringUtils.isNotBlank(goods.getImageIds())) {
			Date date = new Date();
			imageAttachService.deleteImageAttachByGoods(goods.getGoodsId());

			String[] imageIds = goods.getImageIds().split(",");
			ImageAttach imageAttach = null;
			for (String imageId : imageIds) {
				imageAttach = new ImageAttach();
				imageAttach.setImageId(imageId);
				imageAttach.setUpdateTime(date);
				imageAttach.setTargetType(Constants.StoreConstanst.CJYD_GOODS);
				imageAttach.setTargetId(goods.getGoodsId());
				imageAttachService.insertImageAttach(imageAttach);
			}
		}
	}

	//TODO 需要做历史表备份
	private void saveProducts(Goods goods){
		Date date = new Date();
		goods.setCreateTime(date);
		goods.setUpdateTime(date);
		String preBn = RandomStringUtils.randomNumeric(7);
		//生成货品
		//a.多规格商品,多规格货品，商品的库存==所有货品库存之和
		if (StringUtils.isNotBlank(goods.getSpecDesc())){
			SpecDescDto specDescDto = JsonUtil.strToObj(goods.getSpecDesc(), SpecDescDto.class);
			List<Products> newProductsList = specDescDto.getProductsList();
			if(CollectionUtils.isNotEmpty(newProductsList)){
				for (Products products : newProductsList) {
					products.setGoodsId(goods.getGoodsId());
					products.setName(goods.getName());
					products.setGoodsType("normal");
					products.setFreez(0);
					products.setDisabled(0);
					products.setCost(goods.getCost() == null ? 0 : goods.getCost());
					products.setMarketable(goods.getMarketable());
					products.setLastModify(date);
				}
				//保存 新增的货品列表
				int addRow = productsMapper.insertBatchProducts(newProductsList);
				log.info("addRow product row:{}",addRow);
				////保存货品和规格值关系
				//商品规格值
				List<ProductsIndex> productsIndexList = specDescDto.getProductsIndexList();

				List<GoodsSpecIndex> goodsSpecIndices = goodsSpecIndexService.buildGoodsSpecIndexes(goods.getGoodsId(),
						goods.getTypeId(),productsIndexList, newProductsList);

				int specIndexRow = goodsSpecIndexService.insertBatch(goodsSpecIndices);
				log.info("add product specIndexRow:{}",specIndexRow);
			}
		}else {
			//默认单个货品
			String productBn = goods.getProductBn();
			if (StringUtils.isBlank(productBn)) {
				productBn = "P" + preBn + RandomStringUtils.randomAlphanumeric(6);
			}
			Products products = new Products();
			products.setBn(productBn);
			copyGoods2Products(goods,products);
			productsMapper.insertProducts(products);
		}
	}

	/**
	 * 复制商品属性到货品
	 * @param goods
	 * @param products
	 */
	private void copyGoods2Products(Goods goods, Products products){
		products.setBarcode(goods.getBarCode());
		products.setName(goods.getName());
		products.setCost(goods.getCost());
		products.setDisabled(goods.getDisabled());
		products.setFreez(0);
		products.setGoodsId(goods.getGoodsId());
		products.setGoodsType("normal");
		products.setLastModify(new Date());
		products.setMarketable(goods.getMarketable());
		products.setMktprice(goods.getMktprice());
		products.setPrice(goods.getPrice());
		products.setStore(goods.getStore());
		products.setStorePlace(goods.getStorePlace());
		products.setUptime(goods.getUptime());
		products.setWeight(goods.getWeight());
		products.setUnit(goods.getUnit());
		products.setBn(goods.getProductBn());
		products.setIsDefault("true");
	}
	
	/**
     * 修改商品
     * 
     * @param goods 商品信息
     * @return 结果
     */
	@Override
	public int updateGoods(Goods goods) {
		int row = goodsMapper.updateGoods(goods);
		//保存图片
		saveImageGoods(goods);

		if(StringUtils.isBlank(goods.getSpecDesc())){
			//清除之前多规格货品，保存新的货品，多规格变为单规格的时候 TODO

			//更新货品
			List<Products> productsList = productsMapper.selectProductsByGoodsId(goods.getGoodsId());
			if(CollectionUtils.isNotEmpty(productsList)){
				Products products = productsList.get(0);
				copyGoods2Products(goods,products);
				productsMapper.updateProducts(products);
			}
		}
		return row;
	}

	/**
     * 删除商品对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteGoodsByIds(String ids) {
		return goodsMapper.deleteGoodsByIds(Convert.toStrArray(ids));
	}

	@Override
	public int updateMarketable(long goodsId, boolean marketable) {
		int row = goodsMapper.updateMarketable(goodsId, marketable);
		return row;
	}
}
